package com.example.hotel_lxy.ui.activity;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.example.hotel_lxy.R;
import com.example.hotel_lxy.application.ARouterPath;
import com.example.hotel_lxy.bean.BeanBean;
import com.example.hotel_lxy.bean.SetUpZeroBean;
import com.example.hotel_lxy.bean.ZeroSpSourceBean;
import com.example.hotel_lxy.net.Api;
import com.example.hotel_lxy.ui.dialog.DataSelectionDialog;
import com.example.hotel_lxy.ui.dialog.DataSelectionDialogs;
import com.example.hotel_lxy.ui.dialog.StoreDateDialog;
import com.example.hotel_lxy.utils.DatePhotoUtils;
import com.example.hotel_lxy.utils.SPUtils;
import com.ysxsoft.common_base.base.BaseActivity;
import com.ysxsoft.common_base.utils.JsonUtils;
import com.ysxsoft.common_base.utils.ToastUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.jetbrains.annotations.NotNull;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;

/**
 * 修改零点预定页
 */
@Route(path = "/main/SetUpZeroPointReserveActivity")
public class SetUpZeroPointReserveActivity extends BaseActivity implements View.OnClickListener {

    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.text_date)
    TextView textDate;
    @BindView(R.id.text_txl)
    TextView textTxl;
    @BindView(R.id.edit_name)
    EditText editName;
    @BindView(R.id.edit_photo)
    EditText editPhoto;
    @BindView(R.id.line_time)
    LinearLayout lineTime;
    @Autowired
    String id;
    @BindView(R.id.tv_view)
    TextView tvView;
    @BindView(R.id.tv_source)
    TextView tvSource;
    @BindView(R.id.text_add)
    TextView textAdd;
    @BindView(R.id.text_add_mess)
    TextView textAddMess;
    @BindView(R.id.rb_nan)
    RadioButton rbNan;
    @BindView(R.id.rb_nv)
    RadioButton rbNv;
    @BindView(R.id.rg_sex)
    RadioGroup rgSex;
    @BindView(R.id.text_number)
    EditText textNumber;
    @BindView(R.id.edit_qt)
    EditText editQt;
    @BindView(R.id.text_title_name)
    TextView textTitleName;
    @BindView(R.id.text_time)
    TextView textTime;
    private String director_id;
    private String source_id;
    private String time;
    private String time_type;
    List<ZeroSpSourceBean.DataBean.ListBean> list;
    String begin_time;
    public static void start(String id) {
        ARouter.getInstance().build(ARouterPath.getSetUpZeroPointReserveActivity())
                .withString("id", id)
                .navigation();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_zero_point_reserve;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @Override
    public void doWork() {
        super.doWork();
        ARouter.getInstance().inject(this);
        back.setOnClickListener(this);
        textTxl.setOnClickListener(this);
        lineTime.setOnClickListener(this);
        tvView.setOnClickListener(this);
        tvSource.setOnClickListener(this);
        textAdd.setOnClickListener(this);
        textAddMess.setOnClickListener(this);
        textDate.setOnClickListener(this);
        rgSex.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (group.getCheckedRadioButtonId()) {
                    case R.id.rb_nan:
                        rbNv.setChecked(false);
                        break;
                    case R.id.rb_nv:
                        rbNan.setChecked(false);
                        break;
                }
            }
        });
        showDataInfo();
    }

    private void showDataInfo() {
        OkHttpUtils.post()
                .url(Api.POST_ZERO_MODIFY)
                .addHeader("flag", SPUtils.get(SetUpZeroPointReserveActivity.this, "token", "").toString())
                .addParams("id", id)
                .tag(this)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("TAG", "修改零点数据onError   " + e.getMessage());
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.e("TAG", "修改零点数据onResponse   " + response);
                        BeanBean beanBean=JsonUtils.parseByGson(response, BeanBean.class);

                        if (beanBean.getCode().equals("0")) {
                            SetUpZeroBean setUpZeroBean = JsonUtils.parseByGson(response, SetUpZeroBean.class);
                            if(setUpZeroBean.getData().getList()==null){
                                return;
                            }
                            SetUpZeroBean.DataBean.ListBean list = setUpZeroBean.getData().getList();
                            textTitleName.setText("【雅间名称】" + list.getElegant());
                             begin_time = list.getBegin_time();
                            textTime.setText("【到店日期】 " + list.getBegin_time()+" "+list.getWeekArr()+" "+list.getNoon());
                            time=list.getBegin_time();
                            textNumber.setText(""+list.getPeople());
                            editName.setText(""+list.getName());
                            if(list.getSex()==1){
                                rbNan.setChecked(true);
                            }else{
                                rbNv.setChecked(true);
                            }
                            editPhoto.setText(""+list.getMobile());
                            textDate.setText(""+list.getTime());
                            time_type=list.getTime();
                            showData(list.getDirector_id(),list.getSource_id());
                            editQt.setText(""+list.getContent());
                        }else if(beanBean.getCode().equals("4")){
                            SPUtils.put(mContext,"token","");
                            Intent intent = new Intent(mContext, LoginActivity.class).
                                    setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                            return;
                        }


                    }
                });
    }
    private void showData(int director, int source) {
        OkHttpUtils.post()
                .url(Api.POST_ZERO_VIEW)
                .addHeader("flag", SPUtils.get(mContext, "token", "").toString())
                .tag(this)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("TAG", "客户经理onError   " + e.getMessage());
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.e("TAG", "客户经理onResponse   " + response);
                        BeanBean beanBean= JsonUtils.parseByGson(response, BeanBean.class);
                        if(beanBean.getCode().equals("4")){
                            SPUtils.put(mContext,"token","");
                            Intent intent = new Intent(mContext, LoginActivity.class).
                                    setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                            return;
                        }
                        ZeroSpSourceBean zeroSpSourceBean = JsonUtils.parseByGson(response, ZeroSpSourceBean.class);
                        if (beanBean.getCode().equals("0")) {
                            list = zeroSpSourceBean.getData().getList();
                            for(int i=0;i<list.size();i++){
                             String  listid= list.get(i).getId()+"";
                                if(listid.equals(""+director)){
                                    director_id =listid;
                                    tvView.setText("" +list.get(i).getUsername());
                                }
                            }

                        }
                    }
                });
        OkHttpUtils.post()
                .url(Api.POST_ZERO_SOURCE)
                .addHeader("flag", SPUtils.get(mContext, "token", "").toString())
                .tag(this)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("TAG", "客户来源onError   " + e.getMessage());
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.e("TAG", "客户来源onResponse   " + response);
                        BeanBean beanBean= JsonUtils.parseByGson(response, BeanBean.class);
                        if(beanBean.getCode().equals("4")){
                            SPUtils.put(mContext,"token","");
                            Intent intent = new Intent(mContext, LoginActivity.class).
                                    setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                            return;
                        }
                        ZeroSpSourceBean zeroSpSourceBean = JsonUtils.parseByGson(response, ZeroSpSourceBean.class);
                        if (beanBean.getCode().equals("0")) {
                            list = zeroSpSourceBean.getData().getList();
                            for(int i=0;i<list.size();i++){
                                String  listid= list.get(i).getId()+"";
                                if(listid.equals(""+source)){
                                    source_id =listid;
                                    tvSource.setText("" +list.get(i).getName());
                                }
                            }

                        }
                    }
                });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.text_txl:
//                Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
//                startActivityForResult(intent, 0);
                judgePermission();
                break;
            case R.id.line_time:
                showDataTime();
                break;
            case R.id.text_date:
                showDataTime();
                break;
            case R.id.tv_view://客户经理
                DataSelectionDialogs.show(SetUpZeroPointReserveActivity.this, null, Api.POST_ZERO_VIEW).setListener(new DataSelectionDialogs.OnDialogClickListener() {
                    @Override
                    public void onPositiveClick(String id, String name) {
                        director_id = id + "";
                        tvView.setText("" + name);
                    }
                });
                break;
            case R.id.tv_source://客户来源
                DataSelectionDialogs.show(SetUpZeroPointReserveActivity.this, null, Api.POST_ZERO_SOURCE).setListener(new DataSelectionDialogs.OnDialogClickListener() {
                    @Override
                    public void onPositiveClick(String id, String name) {
                        source_id = id + "";
                        tvSource.setText("" + name);
                    }
                });
                break;
            case R.id.text_add:
                showAddZero(1);
                break;
            case R.id.text_add_mess:
                showAddZero(2);
                break;
        }
    }

    private void showDataTime() {
        String time = "00:00-" + time_type;
        String[] two = time.split("-");
        String[] second = two[1].split(":");
        int secondTotalMinute = Integer.valueOf(second[0]) * 60 + Integer.valueOf(second[1]);
        if (secondTotalMinute < 960) {
            StoreDateDialog.show(SetUpZeroPointReserveActivity.this, null, "1",begin_time)
                    .setListener(new StoreDateDialog.OnDialogClickListener() {
                        @Override
                        public void onPositiveClick(String s) {
                            textDate.setText("" + s);
                        }
                    });
        } else if (secondTotalMinute >= 960 && secondTotalMinute < 1439) {
            StoreDateDialog.show(SetUpZeroPointReserveActivity.this, null, "2",begin_time)
                    .setListener(new StoreDateDialog.OnDialogClickListener() {
                        @Override
                        public void onPositiveClick(String s) {
                            textDate.setText("" + s);
                        }
                    });
        }
    }

    private void showAddZero(int type) {
        if (editName.getText().toString().equals("")) {
            ToastUtils.show(SetUpZeroPointReserveActivity.this, "客户姓名不能为空");
            return;
        }
        if (textDate.getText().toString().equals("")) {
            ToastUtils.show(SetUpZeroPointReserveActivity.this, "到店时间不能为空");
            return;
        }
        int sex_type = 1;
        if (rbNan.isChecked()) {
            sex_type = 1;
        } else {
            sex_type = 2;
        }
        OkHttpUtils.post()
                .url(Api.POST_ZERO_MODIFY_SAVE)
                .addHeader("flag", SPUtils.get(SetUpZeroPointReserveActivity.this, "token", "").toString())
                .addParams("id", id)
                .addParams("people", textNumber.getText().toString())
                .addParams("name", editName.getText().toString())
                .addParams("sex", sex_type + "")
                .addParams("mobile", editPhoto.getText().toString())
                .addParams("time", textDate.getText().toString())
                .addParams("director_id", director_id)
                .addParams("content", editQt.getText().toString())
                .addParams("source_id", source_id)
                .addParams("type", type + "")
                .tag(this)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("TAG", "零点预定onError   " + e.getMessage());
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.e("TAG", "零点预定onResponse   " + response);
                        BeanBean beanBean = JsonUtils.parseByGson(response, BeanBean.class);
                        if (beanBean.getCode().equals("0")) {
                            ToastUtils.show(SetUpZeroPointReserveActivity.this, beanBean.getMsg());
                            finish();
                        }else   if(beanBean.getCode().equals("4")){
                            SPUtils.put(mContext,"token","");
                            Intent intent = new Intent(mContext, LoginActivity.class).
                                    setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                            return;
                        }
                        else {
                            ToastUtils.show(SetUpZeroPointReserveActivity.this, beanBean.getMsg());
                        }

                    }
                });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 0:
                if (data == null) {
                    return;
                }
                Uri uri = data.getData();
                String[] contacts = DatePhotoUtils.getPhoneContacts(SetUpZeroPointReserveActivity.this, uri);
                editName.setText("" + contacts[0]); //contacts[1]
                editPhoto.setText("" + contacts[1]);
                break;
        }
    }

    protected void judgePermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // 检查该权限是否已经获取
            // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
            //手机状态权限
            String[] SdCdPermission = {Manifest.permission.READ_CONTACTS};
            if (ContextCompat.checkSelfPermission(this, SdCdPermission[0]) != PackageManager.PERMISSION_GRANTED) {
                // 如果没有授予该权限，就去提示用户请求
                ActivityCompat.requestPermissions(this, SdCdPermission, 350);
            }else{
                Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
                startActivityForResult(intent, 0);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NotNull @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        boolean hasAllGranted = true;
        //判断是否拒绝  拒绝后要怎么处理 以及取消再次提示的处理
        for (int grantResult : grantResults) {
            if (grantResult == PackageManager.PERMISSION_DENIED) {
                hasAllGranted = false;
                break;
            }
        }
        if (hasAllGranted) { //同意权限做的处理,开启服务提交通讯录
            Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
            startActivityForResult(intent, 0);

        } else {    //拒绝授权做的处理，弹出弹框提示用户授权
            dealwithPermiss(SetUpZeroPointReserveActivity.this, permissions[0]);
        }
    }

    public void dealwithPermiss(final Activity context, String permission) {
        if (!ActivityCompat.shouldShowRequestPermissionRationale(context, permission)) {
            AlertDialog.Builder builder = new AlertDialog.Builder(SetUpZeroPointReserveActivity.this);
            builder.setTitle("操作提示")
                    .setMessage("注意：当前缺少必要权限！\n请点击“设置”-“权限”-打开所需权限\n最后点击两次后退按钮，即可返回")
                    .setPositiveButton("去授权", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                            Uri uri = Uri.fromParts("package", context.getApplicationContext().getPackageName(), null);
                            intent.setData(uri);
                            context.startActivity(intent);
                        }
                    })
                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Toast.makeText(SetUpZeroPointReserveActivity.this, "取消授权", Toast.LENGTH_SHORT).show();
                        }
                    }).show();

        }
    }
}